package com.zf.nacos.config;

import com.alibaba.cloud.nacos.NacosConfigManager;
import com.alibaba.cloud.nacos.NacosConfigProperties;
import com.alibaba.nacos.api.config.ConfigType;
import com.alibaba.nacos.api.config.listener.AbstractListener;
import com.alibaba.nacos.api.exception.NacosException;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;


/**
 * nacos服务配置相关
 */
@RestController
@RequestMapping("/cfg")
public class NacosConfigTestController {

    /**
     * application和bootstrap中配置的 nacos配置中心信息：发布、删除配置、监听配置文件变化
     */
    @Resource
    private NacosConfigManager configManager;
    /**
     * nacos配置中心的配置信息
     */
    @Resource
    private NacosConfigProperties nacosConfigProperties;

    /**
     * 获取配置
     */
    @GetMapping("/getConfig")
    public String getConfig(@RequestParam(name = "dataId") String dataId) throws NacosException {
        String config = configManager.getConfigService().getConfig(dataId, nacosConfigProperties.getGroup(), 5000);
        return config;
    }

    /**
     * 发布配置, 如果"dataId+group"已存在则替换原本的内容
     */
    @GetMapping("/publishConfig")
    public boolean publishConfig() throws NacosException {
        boolean result = configManager.getConfigService().publishConfig("aaa.yaml", nacosConfigProperties.getGroup(), "aaa: 222\nbbb: 444", ConfigType.YAML.getType());
        return result;
    }

    /**
     * 删除配置
     */
    @GetMapping("/removeConfig")
    public boolean removeConfig() throws NacosException {
        boolean result = configManager.getConfigService().removeConfig("aaa.yaml", nacosConfigProperties.getGroup());
        return result;
    }


    /**
     * 监听器
     */
    AbstractListener listener = new AbstractListener() {
        @Override
        public void receiveConfigInfo(String configInfo) {
            System.out.println(configInfo);
        }
    };

    /**
     * 监听某个配置文件的变化
     */
    @GetMapping("/addListener")
    public String addListener() throws NacosException {
        configManager.getConfigService().addListener("aaa.yaml", nacosConfigProperties.getGroup(), listener);
        return "success";
    }

    /**
     * 移除监听器: 必须要和注册的监听器是一个对象，否则无法移除
     */
    @GetMapping("/removeListener")
    public String removeListener() {
        configManager.getConfigService().removeListener("aaa.yaml", nacosConfigProperties.getGroup(), listener);
        return "success";
    }


}
